项目如何配置 electron-builder 改图标、改背景
概述
本节介绍如何使用 electron-builder 自定义应用图标和 DMG 安装程序的背景图片。通过配置 buildResources 目录和 dmg 相关选项,可以实现 macOS 安装界面的视觉定制。
资源文件准备
图标文件格式要求
| 平台 | 格式 | 推荐尺寸 |
|---|---|---|
| macOS | .icns | 1024x1024 |
| Windows | .ico | 256x256 |
| Linux | .png | 512x512 |
DMG 背景图片
- 格式:
.tiff或.png - 推荐尺寸:660x400 像素
- 放置在
buildResources目录中
project/
├── build/ ← buildResources 目录
│ ├── icon.icns ← macOS 图标
│ ├── icon.ico ← Windows 图标
│ ├── icon.png ← Linux 图标
│ └── background.tiff ← DMG 安装背景
├── src/
└── electron-builder.config.js
text
electron-builder 配置
完整配置文件
// electron-builder.config.js
module.exports = {
appId: 'com.example.myapp',
productName: 'MyApp',
copyright: 'Copyright © 2026',
// 资源目录配置
directories: {
output: 'dist',
buildResources: 'build' // 指定资源文件目录
},
// macOS 配置
mac: {
category: 'public.app-category.productivity',
target: 'dmg',
icon: 'build/icon.icns', // 应用图标
},
// DMG 安装程序配置
dmg: {
title: '${productName} ${version}',
icon: 'build/icon.icns',
// DMG 背景图片
background: 'build/background.tiff',
// 窗口尺寸
window: {
width: 660,
height: 400
},
// 图标和应用程序快捷方式的位置
contents: [
{ x: 180, y: 170, type: 'file', path: '${productName}.app' },
{ x: 480, y: 170, type: 'link', path: '/Applications' }
],
iconSize: 100
},
// Windows 配置
win: {
target: 'nsis',
icon: 'build/icon.ico'
},
// Linux 配置
linux: {
target: 'AppImage',
icon: 'build/icon.png'
}
}
javascript
DMG 背景图设置要点
dmg: {
// background 路径相对于 buildResources 目录
background: 'build/background.tiff',
// window 尺寸需与背景图尺寸匹配
window: {
width: 660, // 与背景图宽度一致
height: 400 // 与背景图高度一致
},
// contents 控制图标位置
contents: [
// 应用图标位置
{ x: 180, y: 170, type: 'file', path: '${productName}.app' },
// Applications 快捷方式位置
{ x: 480, y: 170, type: 'link', path: '/Applications' }
]
}
javascript
图标制作工具
| 工具 | 用途 | 说明 |
|---|---|---|
electron-icon-maker | 自动生成各平台图标 | 输入一张 1024x1024 PNG 即可 |
iconutil (macOS) | 生成 .icns | 系统自带命令行工具 |
png2icons | PNG 转 .ico/.icns | npm 包 |
| 在线工具 | 快速转换 | favicon.io、iconverticons.com |
使用 electron-icon-maker
# 安装
npm install -D electron-icon-maker
# 生成图标(需要一张 1024x1024 的 PNG 源图)
npx electron-icon-maker --input=logo.png --output=./build
bash
构建命令
# 仅构建 Electron 部分
npm run build:electron
# 构建指定平台
npx electron-builder --mac
npx electron-builder --win
npx electron-builder --linux
bash
常见问题
| 问题 | 原因 | 解决方案 |
|---|---|---|
| DMG 背景不显示 | 路径配置错误 | 确认 background 路径相对于项目根目录 |
| 图标未更新 | 缓存问题 | 清理 dist 目录后重新构建 |
| .icns 格式错误 | 尺寸不符合要求 | 使用 electron-icon-maker 自动生成 |
| Windows 图标模糊 | ico 包含尺寸不足 | 确保 ico 包含 16/32/48/256 多种尺寸 |
实践要点
- 将图标和背景图片统一放在
build/目录,通过directories.buildResources指定 - DMG 背景图尺寸需与
dmg.window配置的尺寸匹配 dmg.contents控制安装界面中应用图标和 Applications 快捷方式的位置- 推荐使用
electron-icon-maker从一张高清 PNG 自动生成所有平台的图标格式 - 图标文件名默认使用
icon.icns/icon.ico/icon.png,electron-builder 会自动识别
↑